/*
 * ! Ext JS Library 3.2.1 Copyright(c) 2006-2010 Ext JS, Inc.
 * licensing@extjs.com http://www.extjs.com/license
 */
NoticeFeedPanel = function() {
	NoticeFeedPanel.superclass.constructor.call(this, {
				region : 'west',
				title : '消息分类',
				split : true,
				width : 225,
				minSize : 175,
				maxSize : 400,
				collapsible : true,
				margins : '0 0 0 0',
				cmargins : '0 0 0 0',
				rootVisible : false,
				lines : false,
				autoScroll : true,
				root : new Ext.tree.TreeNode('我的消息'),
				collapseFirst : false
			});

	// this.feeds =this.root;

	this.getSelectionModel().on({
				'beforeselect' : function(sm, node) {
					return node.isLeaf();
				},
				'selectionchange' : function(sm, node) {
					if (node) {
						this.fireEvent('feedselect', node.attributes);
					}
					// this.getTopToolbar().items.get('delete').setDisabled(!node);
				},
				scope : this
			});

	this.addEvents({
				feedselect : true
			});

	// this.on('contextmenu', this.onContextMenu, this);
};

Ext.extend(NoticeFeedPanel, Ext.tree.TreePanel, {
			selectFeed : function(no) {
				var feed = this.root.item(no);
				if (feed) {
					// alert(feed);
					feed.select();
				}
			},

			addFeed : function(attrs, inactive, preventAnim) {

				/*
				 * var exists = this.getNodeById(attrs.url); if(exists){
				 * if(!inactive){ exists.select(); exists.ui.highlight(); }
				 * return; }
				 */
				Ext.apply(attrs, {
					iconCls : 'feed-icon',
					leaf : true,
					cls : 'feed'
						// id: attrs.url
					});
				var node = new Ext.tree.TreeNode(attrs);
				this.root.appendChild(node);
				if (!inactive) {
					if (!preventAnim) {
						Ext.fly(node.ui.elNode).slideIn('l', {
									callback : node.select,
									scope : node,
									duration : .4
								});
					} else {
						node.select();
					}
				}
				return node;
			},

			// prevent the default context menu when you miss the node
			afterRender : function() {
				NoticeFeedPanel.superclass.afterRender.call(this);
				this.el.on('contextmenu', function(e) {
							e.preventDefault();
						});
			}
		});

Uec3.NoticeWindow = Ext.extend(Ext.app.Module, {
			// id : 'notice',
			// type : 'common/notice',
			noticeGrid : null,
			noticeDetailCaller : null,

			/**
			 * Initialize this module. This func tion is called at startup (page
			 * load/refresh).
			 */
			init : function(initParams) {
				this.noticeDetailCaller = new Ext.data.Connection();
				this.noticeDetailCaller.on('beforerequest', function() {
							Ext.MessageBox.wait("消息资料查询中...", "系统提示");
						});
				this.noticeDetailCaller.on('requestcomplete', function() {
							Ext.MessageBox.hide();
						});
			},

			detailNotice : function(noticeId) {

				this.noticeDetailCaller.request({
						url : Uec3.App.Constants.homeUrl + '/notice/detail.do?noticeIds='+noticeId,
						success : function(o) {
							eval("var notice=" + o.responseText);
							
							if (notice.jsModuleId && notice.jsModuleId != "" & !notice.dealed) {
								// this.app.getDesktop().launchWindow(notice.jsModuleId);
								this.app.makeRequest(notice.jsModuleId, notice, function(m) {
											if (m.curWindow) {
												this.noticeDetailWindow = m.curWindow;
												this.noticeDetailWindow.on({
															'beforeclose' : {
																fn : function(win) {
																	this.noticeGrid.store.reload();
																},
																scope : this
															}
														});
												// this.doTrigger();
			
											}
										}, this);
							} else {
								var win = this.app.getDesktop().createWindow({
											title : '消息详情: ' + notice.title,
											width : 540,
											height : 380,
											html : "<p>" + notice.content + "</p>",
											iconCls : 'bogus-icon',
											shim : false,
											animCollapse : false,
											constrainHeader : true,
											layout : "fit"
										});
								win.show();
							}

						},
						failure : function() {
							Ext.MessageBox.alert('系统提示', '获取消息详情失败!');
						},
						scope : this
				});
			},

			getComponents : function(rowIndex) {

				var notice_ds;
				// var notice_grid;
				// var notice_ajax = new Ext.data.Connection();
				// var desktop = this.app.getDesktop();

				var theModule = this;
				var app = this.app;

				var renderContent = function(value, cellmeta, record, rowIndex, columnIndex, store) {

//					if (value.length > 30) {
//						return value.substring(0, 30) + "......";
//					}
					return value;

				};

				var renderType = function(value, cellmeta, record, rowIndex, columnIndex, store) {

					return value == "1" ? "站内信" : "系统通知";

				};

				var actionCol = {
					header : "操作",
					width : 30,
					sortable : false,
					dataIndex : 'id',
					renderer : this.moduleActionRenderer({
								func : "detailNotice",
								desc : "详情",
								reader : function(value, cellmeta, record, rowIndex, columnIndex, store) {
									return value;
								}
							})
				};
				var componentInitsNotice = function() {

					// 初始化notice_grid表格对象
					var sm = new Ext.grid.CheckboxSelectionModel({
								// dataIndex : "id",
								// width : 20,
								moveEditorOnEnter : true,
								singleSelect : false
							});

					notice_ds = new Ext.data.Store({

								proxy : new Ext.data.HttpProxy({
											url : Uec3.App.Constants.homeUrl + '/notice/paging.do'
										}),
								baseParams : {
									start : 0,
									limit : 20,
									type : "{dealed:false}"
								},
								reader : new Ext.data.JsonReader({
											totalProperty : 'total',
											root : 'items'
										}, [{
													name : 'id'
												}, {
													name : 'title'
												}, {
													name : 'senderId'
												}, {
													name : 'noticeType'
												}, {
													name : 'dealed'
												}, {
													name : 'readen'
												}, {
													name : 'jsModuleId'
												}, {
													name : 'jsArgs'
												}, {
													name : 'content'
												}, {
													name : 'gmtCreate'/*,
													type : 'date',
													dateFormat : 'Y-m-d'*/
												}]),
								remoteSort : true,
								// 默认排序字段
								sortInfo : {
									field : "id",
									direction : "asc"
								}

							});
					var notice_colModel = new Ext.grid.ColumnModel([sm, actionCol, {
								header : "标题",
								width : 90,
								sortable : false,
								dataIndex : 'title'
							}, {
								header : "senderId",
								width : 60,
								dataIndex : 'senderId',
								hidden : true
							}, {
								header : "jsModuleId",
								width : 60,
								dataIndex : 'jsModuleId',
								hidden : true
							}, {
								header : "readen",
								width : 60,
								dataIndex : 'readen',
								hidden : true
							}, {
								header : "jsArgs",
								width : 60,
								dataIndex : 'jsArgs',
								hidden : true
							}, {
								header : "消息类型",
								width : 50,
								dataIndex : 'noticeType',
								renderer : renderType
							}, {
								header : "摘要",
								width : 200,
								sortable : false,
								dataIndex : 'content',
								renderer : renderContent
							}, {
								header : "时间",
								width : 90,
								sortable : false/*,
								renderer : Ext.util.Format.dateRenderer('Y-m-d'),
								dataIndex : 'gmtCreate'*/
							}

					]);

					// create the Grid
					theModule.noticeGrid = new Ext.grid.GridPanel({
								title : '待处理消息',
								region : 'center',
								iconCls : 'acc-icon',
								enableColumnMove : false,
								enableColumnMoveResize : false,
								stripeRows : true,
								// autoHeight : true,
								loadMask : {
									msg : "...加载数据中"
								},
								store : notice_ds,
								cm : notice_colModel,
								sm : sm,
								viewConfig : {
									forceFit : true,
									columnsText : '显示的列',
									scrollOffset : 20,
									sortAscText : '升序',
									sortDescText : '降序',
									getRowClass : function(record,rowIndex,rowParams,store){
										//未阅读加粗
										if(record.data.readen){
											return 'x-grid-record-gray';
										}else {
											return 'x-grid-record-blank';
										}
										
								   	}
								},
								act : function(text, url, callback) {
									var chkedItems = sm.getSelections();
									if (!chkedItems || chkedItems.length == 0) {
										Ext.MessageBox.alert('系统提示', '请选择消息!');
										return;
									}
									Ext.Msg.confirm('系统确认', '确认' + text + '？', function(btn) {
												if (btn == 'yes') {
													var chkedIds = "";
													for (var i = 0; i < chkedItems.length; i++) {
														chkedIds = chkedIds + "," + chkedItems[i]["id"];
													}
													Ext.Ajax.request({
																url : url + '?noticeIds=' + chkedIds,
																// baseParams :
																// {actNotices:chkedIds},
																success : function(o) {
																	eval("var p=" + o.responseText);
																	if (p.success) {
																		// notice_ds.remove(chkedItems);
																		if (callback) {
																			callback.call(this, chkedItems);
																		} else {
																			notice_ds.reload();
																		}
																		Ext.MessageBox.alert('系统提示', text + '成功!');

																	} else {
																		Ext.MessageBox.alert('系统提示', text + '失败!');
																	}

																},
																failure : function() {
																	Ext.MessageBox.alert('系统提示', text + '失败!');
																},
																scope : this
															});
												}
											}, this);

								},
								tbar : new Ext.app.ModuleToolbar(['-', {
											text : '删除消息',
											handler : function() {
												theModule.noticeGrid.act("删除消息", Uec3.App.Constants.homeUrl + '/notice/remove.do', function(chkedItems) {
															notice_ds.remove(chkedItems);
														});
											}
										}/*
											 * , '-', { split : true, text :
											 * '处理消息', tooltip : { title :
											 * '处理消息', text : '标记消息为已处理或未处理' },
											 * menu : { width : 120, items : [{
											 * text : '标记为已处理', checked : false,
											 * group : 'rp-group', checkHandler :
											 * function() {
											 * theModule.noticeGrid.act("标记消息为已处理",
											 * Uec3.App.Constants.homeUrl +
											 * '/notice/deal.do'); }, scope :
											 * this, iconCls : 'preview-bottom' }, {
											 * text : '标记为未处理', checked : false,
											 * group : 'rp-group', checkHandler :
											 * function() {
											 * theModule.noticeGrid.act("标记消息为未处理",
											 * Uec3.App.Constants.homeUrl +
											 * '/notice/revert.do'); }, scope :
											 * this, iconCls : 'preview-right' }] } }
											 */]),
								bbar : new Ext.PagingToolbar({
											pageSize : 20,
											store : notice_ds,
											displayInfo : true,
											displayMsg : '第 {0} - {1} 条  共 {2} 条',
											emptyMsg : "没有记录"
										})

							});

					if (notice_ds.load() && notice_ds.getCount() > 0) {
						app.lastNoticeId = notice_ds.getAt(0)["id"];
					}
				};
				/*
				 * var controlNoticeEvent = function() {
				 * notice_ajax.on('beforerequest', function() {
				 * Ext.MessageBox.wait("消息资料查询中...", "系统提示"); });
				 * notice_ajax.on('requestcomplete', function() {
				 * Ext.MessageBox.hide(); }); };
				 */
				componentInitsNotice();

				// controlNoticeEvent();

				var feeds = new NoticeFeedPanel();
				feeds.addFeed({
							noticeType : "{dealed:false}",
							text : '待处理消息',
							callback : function() {
								if (notice_ds.getCount() > 0) {
									app.lastNoticeId = notice_ds.getAt(0)["id"];
								}
							}
						}, true);
				feeds.addFeed({
							noticeType : "{dealed:true}",
							text : '已处理消息'
						}, true);
				feeds.on('feedselect', function(feed) {
					// notice_ds.proxy.conn.url = feed.url;
					theModule.noticeGrid.setTitle(feed.text);
					notice_ds.setBaseParam("type", feed.noticeType);
					notice_ds.setBaseParam("start", 0);
					notice_ds.reload();
						// if (notice_ds.load() && feed.callback) {
						// feed.callback.call(this);
						// }

					});

				// feeds.selectFeed(0);
				return [feeds, theModule.noticeGrid];

			},

			/**
			 * Create this modules window here.
			 */
			createWindow : function() {
				var desktop = this.app.getDesktop();
				var win = desktop.getWindow('notice');
				if (!win) {
					win = desktop.createWindow({
								id : 'notice',
								title : '我的消息',
								width : '100%',
								closable : true,
								height : 500,
								iconCls : 'acc-icon',
								shim : false,
								animCollapse : false,
								constrainHeader : true,
								maximizable : true,
								maximized : true,
								taskbuttonTooltip : "我的消息列表",
								layout : "border",
								tools : [{
											id : 'refresh',
											handler : Ext.emptyFn,
											scope : this
										}],
								items : this.getComponents()
							});

				}
				win.creator = this;
				win.show();
			}
		});